package com.sh.data.engine.domain.workspace.manager.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sh.data.engine.common.constants.HttpStatus;
import com.sh.data.engine.common.constants.code.BizCodes;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.domain.authority.service.RoleService;
import com.sh.data.engine.domain.authority.service.TokenService;
import com.sh.data.engine.domain.base.model.PageResult;
import com.sh.data.engine.domain.feign.FeignUser;
import com.sh.data.engine.domain.feign.FeignUserPage;
import com.sh.data.engine.domain.workspace.manager.model.domain.UserDomain;
import com.sh.data.engine.domain.workspace.manager.model.domain.UserMeta;
import com.sh.data.engine.domain.workspace.manager.model.domain.UserYunQiaoDomain;
import com.sh.data.engine.domain.workspace.manager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户服务，从云巧获取数据
 *
 * @author: mengzheng.mhc
 * @date: 2024/6/19 12:51
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    //该id在不同的环境不一样
    @Value("${super.admin.id}")
    private String SUPER_ADMIN;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private FeignUserPage feignUserPage;

    private static FeignUser feignUser = SpringUtil.getBean(FeignUser.class);

    private UserDomain getAndExtractUser(String userId) {
        UserYunQiaoDomain user = feignUser.getMap(userId);
        UserDomain userDomain = new UserDomain();
        userDomain.setUserName(user.getUserName());
        userDomain.setId(user.getId());
        //如果列表为空，则值为null
        if (CollectionUtils.isNotEmpty(user.getEmails())) {
            userDomain.setEmail(user.getEmails().get(0).get("value"));
        }
        if (CollectionUtils.isNotEmpty(user.getPhoneNumbers())) {
            userDomain.setPhoneNumber(user.getPhoneNumbers().get(0).get("value"));
        }
        userDomain.setDisplayName(user.getDisplayName());
        userDomain.setDeleted(user.isDeleted());
        userDomain.setActive(user.isActive());
        userDomain.setGroups(user.getGroups());
        userDomain.setUserToken(tokenService.getToken(userId));
        UserMeta userMeta = new UserMeta(user.getMeta().getCreated(), user.getMeta().getLastModified(), user.getMeta().getResourceType());
        userDomain.setCreated(userMeta.getCreated());
        userDomain.setLastModified(userMeta.getLastModified());
        //判断是否是超级管理员
        userDomain.setIsAuth(userId.equals(SUPER_ADMIN) ? 1 : 0);
        return userDomain;
    }

    @Override
    public PageResult<UserDomain> getUserPageList(Integer pageNum, Integer pageSize) {
        JSONObject mapResult = feignUserPage.getMap(pageNum, pageSize, null);
        Object totalResultsObj = mapResult.get("totalResults");
        Long totalResults;
        if (totalResultsObj instanceof Integer) {
            totalResults = ((Integer) totalResultsObj).longValue();
        } else if (totalResultsObj instanceof Long) {
            totalResults = (Long) totalResultsObj;
        } else {
            throw new IllegalArgumentException("totalResults must be an Integer or Long");
        }
        Integer startIndex = (Integer) mapResult.get("startIndex");
        Integer itemsPerPage = (Integer) mapResult.get("itemsPerPage");
        Integer totalPages = Math.toIntExact(totalResults / itemsPerPage) + 1;
        List<Object> resources = getResources(mapResult);
        PageResult<UserDomain> resultPage = new PageResult<>();
        resultPage.setTotalPages(totalPages);
        //对result去重，空间拥有者可能是超级管理员，保留一条记录即可
        resultPage.setResult(this.convertFromYunqiaoUserList(this.domainParse(resources)));
        resultPage.setTotalElements(totalResults);
        resultPage.setPageNum(startIndex);
        resultPage.setPageSize(pageSize);
        return resultPage;
    }

    private List<UserYunQiaoDomain> domainParse(List<Object> resources) {
        List<UserYunQiaoDomain> domainList = new ArrayList<>();
        for (int i = 0; i < resources.size(); i++) {
            // 将list中的数据转成json字符串
            String jsonObject = JSON.toJSONString(resources.get(i));
            //将json转成需要的对象
            UserYunQiaoDomain user = JSONObject.parseObject(jsonObject, UserYunQiaoDomain.class);
            domainList.add(user);
        }
        return domainList;
    }

    private List<UserDomain> convertFromYunqiaoUserList(List<UserYunQiaoDomain> userList) {
        //将List<UserYunQiaoDomain>转换为List<UserDomain>
        List<UserDomain> userDomainList = new ArrayList<>();
        for (UserYunQiaoDomain user : userList) {
            UserDomain userDomain = new UserDomain();
            userDomain.setUserName(user.getUserName());
            userDomain.setId(user.getId());
            //如果列表为空，则值为null
            if (CollectionUtils.isNotEmpty(user.getEmails())) {
                userDomain.setEmail(user.getEmails().get(0).get("value"));
            }
            if (CollectionUtils.isNotEmpty(user.getPhoneNumbers())) {
                userDomain.setPhoneNumber(user.getPhoneNumbers().get(0).get("value"));
            }
            userDomain.setDisplayName(user.getDisplayName());
            userDomain.setDeleted(user.isDeleted());
            userDomain.setActive(user.isActive());
            userDomain.setGroups(user.getGroups());
            //判断是否是超级管理员
            userDomain.setIsAuth(user.getId().equals(SUPER_ADMIN) ? 1 : 0);
            UserMeta userMeta = new UserMeta(user.getMeta().getCreated(), user.getMeta().getLastModified(), user.getMeta().getResourceType());
            userDomain.setCreated(userMeta.getCreated());
            userDomain.setLastModified(userMeta.getLastModified());
            userDomainList.add(userDomain);

        }
        return userDomainList;
    }

    @Override
    public List<UserDomain> findByUserNameOrEmail(String email, String userName) {
        if (!userName.isEmpty() && email.isEmpty()) {
            //default pageSize
            Integer pageSize = 99999;
            JSONObject map = feignUserPage.getMap(1, pageSize, "userName eq " + userName);
            List<Object> resources = getResources(map);
            return this.convertFromYunqiaoUserList(this.domainParse(resources));
        } else if (!email.isEmpty() && userName.isEmpty()) {
            //default pageSize
            Integer pageSize = 99999;
            JSONObject map = feignUserPage.getMap(1, pageSize, "emails eq " + email);
            List<Object> resources = getResources(map);
            return this.convertFromYunqiaoUserList(this.domainParse(resources));
        } else if (!email.isEmpty()) {
            throw new BusinessException("Composite condition query is not supported");
        } else {
            return null;
        }
    }

    @Override
    public Boolean isAccessAllowed(String userId, String requestURI) {
        return true;
    }

    /**
     * @param guid
     * @return role isAuth
     */
    @Override
    public UserDomain getUserById(String guid) {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        UserDomain user = this.getAndExtractUser(guid);
        try {
            user.setRoleId(roleService.getRoleIdByUserId(guid));
        } catch (Exception e) {
            throw new BusinessException(BizCodes.ROLE_NOT_FOUND_ERROR,
                    HttpStatus.BAD_REQUEST);
        }
        user.setRoleName(roleService.getById(roleService.getRoleIdByUserId(guid)).getRoleName());
        return user;
    }

    @Override
    public String getUserNameById(String guid) {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        UserDomain user = this.getAndExtractUser(guid);
        return user.getUserName();
    }

    @Override
    public UserDomain getUserDetailByIdWithoutRole(String guid) {
        return this.getAndExtractUser(guid);
    }

    @Override
    public List<UserDomain> getUserList(String userName, Integer pageNum, Integer pageSize) {
        JSONObject map = feignUserPage.getMap(pageNum, pageSize, "userName eq " + userName);
        List<Object> resources = getResources(map);
        return this.convertFromYunqiaoUserList(this.domainParse(resources));
    }

    @Override
    public List<UserDomain> getUserListWithoutAdmin(String userName, Integer pageNum, Integer pageSize) {
        JSONObject map = feignUserPage.getMap(pageNum, pageSize, "userName eq " + userName);
        List<Object> resources = getResources(map);
        List<UserDomain> userDomains = this.convertFromYunqiaoUserList(this.domainParse(resources));
        //剔除resources中的超级管理员
        userDomains.removeIf(user -> user.getId().equals(SUPER_ADMIN));
        return userDomains;
    }

    @Override
    public Map<String, String> getMapByUserIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Map.of();
        }
        //用逗号拼接ids
        String idsStr = String.join(",", ids);
        //批查询云巧用户
        JSONObject mapResult = feignUserPage.getMap(1, 99999, "externalIds eq " + idsStr);
        Object totalResults = mapResult.get("totalResults");
        Object startIndex = mapResult.get("startIndex");
        Object itemsPerPage = mapResult.get("itemsPerPage");
        Integer totalPages = (Integer) totalResults / (Integer) itemsPerPage;

        List<Object> resources = getResources(mapResult);
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < resources.size(); i++) {
            // 将list中的数据转成json字符串
            String jsonObject = JSON.toJSONString(resources.get(i));
            //将json转成需要的对象
            UserYunQiaoDomain user = JSONObject.parseObject(jsonObject, UserYunQiaoDomain.class);
            map.put(ids.get(i), user.getUserName());
        }
        return map;
    }

    @Override
    public Map<String, UserDomain> getMapUserDomainByUserIds(List<String> ids) {
        //用逗号拼接ids
        String idsStr = String.join(",", ids);
        //批查询云巧用户
        JSONObject mapResult = feignUserPage.getMap(1, 99999, "externalIds eq " + idsStr);
        List<Object> resources = getResources(mapResult);
        HashMap<String, UserDomain> map = new HashMap<>();
        for (int i = 0; i < resources.size(); i++) {
            // 将list中的数据转成json字符串
            String jsonObject = JSON.toJSONString(resources.get(i));
            //将json转成需要的对象
            UserYunQiaoDomain user = JSONObject.parseObject(jsonObject, UserYunQiaoDomain.class);
            map.put(ids.get(i), this.convertFromYunqiaoUserList(List.of(user)).get(0));
        }
        return map;
    }

    @Override
    public List<UserDomain> findAll() {
        JSONObject map = feignUserPage.getMap(1, 99999, null);
        return this.convertFromYunqiaoUserList(this.domainParse(getResources(map)));
    }

    @Override
    public List<UserDomain> findRegularUsers() {
        //逻辑：所有用户剔除超管用户
        JSONObject map = feignUserPage.getMap(1, 99999, null);
        List<UserDomain> userDomains = this.convertFromYunqiaoUserList(this.domainParse(getResources(map)));
        //剔除resources中的超级管理员
        userDomains.removeIf(user -> user.getId().equals(SUPER_ADMIN));
        return userDomains;
    }

    private List<Object> getResources(JSONObject map) {
        return (List<Object>) map.get("resources");
    }

}
